package ciyuan.dataStore;

import ciyuan.Utils;
import ciyuan.wrap.Wrapper;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

public class PlayerIp {

    private final File dataFile;
    private Object config;
    private final ReentrantLock lock;

    public PlayerIp(File dataFile) {
        this.dataFile = dataFile;
        this.lock = new ReentrantLock(true);
        try {
            if (!dataFile.exists()) {
                dataFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.config = Wrapper.INSTANCE.loadConfiguration(dataFile);
    }

    private void save() {
        lock.lock();
        try {
            Wrapper.INSTANCE.saveConfiguration(config, dataFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        lock.unlock();
    }

    private void load() {
        lock.lock();
        this.config = Wrapper.INSTANCE.loadConfiguration(dataFile);
        lock.unlock();
    }

    public boolean isEqual(String playerName, String ip) {
        load();
        Wrapper.INSTANCE.logMsg("判断IP 预期:" + Wrapper.INSTANCE.configGetString(config, playerName) + ",实际:" + Utils.getMd5(ip));
        return Objects.equals(Utils.getMd5(ip), Wrapper.INSTANCE.configGetString(config, playerName));
    }

    public void setIp(String playerName, String ip) {
        Wrapper.INSTANCE.configSetValue(config, playerName, Utils.getMd5(ip));
        save();
    }
}
